×
☰ See All Chapters

JPA One-to-One Unidirectional Association Mapping

One-To-One mapping is an association between one persistence object and another one related persistence object. If one persistence object uses other and in back if other is not using the first persistence object then it becomes unidirectional. If one persistence object uses other and in back if other using the first persistence object then it becomes bidirectional.

As an example, the association between Employee and Employeedetail, Here One Employee has one Employeedetail. Employee needs Employeedetail and Employeedetail does not need Employee and hence it becomes unidirectional.

JPA One-to-One unidirectional Association Mapping Example

Now let us see how this mapping is done in persistence class by going through an example.  The following code shows how to do one-to-one unidirectional association mapping. We created two entities, Employee and Employeedetail. In the Employee class we annotate the Employeedetail field by @OneToOne annotation.

Database script (MySQL)

DROP TABLE EMPLOYEEDETAIL;

COMMIT;

 

DROP TABLE EMPLOYEE;

COMMIT;

 

CREATE TABLE EMPLOYEE (

EMPID INT(10) PRIMARY KEY AUTO_INCREMENT,

NAME VARCHAR(50)

);

 

CREATE TABLE EMPLOYEEDETAIL (

EMPDETAILID  INT(10) PRIMARY KEY AUTO_INCREMENT,

EMPID INT(10),

STATE VARCHAR(20),

AGE NUMERIC(10),

CONSTRAINT FOREIGN KEY (EMPID) REFERENCES EMPLOYEE (EMPID)

);

 

pom.xml

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"

        xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">

        <modelVersion>4.0.0</modelVersion>

        <groupId>com.java4coding</groupId>

        <artifactId>121_UnidirectionalAssociationMapping</artifactId>

        <packaging>jar</packaging>

        <version>1.0-SNAPSHOT</version>

        <name>121_UnidirectionalAssociationMapping</name>

        <url>https://maven.apache.org</url>

        <dependencies>

                <dependency>

                        <groupId>junit</groupId>

                        <artifactId>junit</artifactId>

                        <version>3.8.1</version>

                        <scope>test</scope>

                </dependency>

                <dependency>

                        <groupId>org.eclipse.persistence</groupId>

                        <artifactId>javax.persistence</artifactId>

                        <version>2.0.0</version>

                </dependency>

 

                <dependency>

                        <groupId>org.hibernate</groupId>

                        <artifactId>hibernate-entitymanager</artifactId>

                        <version>4.2.8.Final</version>

                </dependency>

 

                <dependency>

                        <groupId>mysql</groupId>

                        <artifactId>mysql-connector-java</artifactId>

                        <version>8.0.11</version>

                </dependency>

        </dependencies>

</project>

 

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="https://java.sun.com/xml/ns/persistence"

        xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"

        xsi:schemaLocation="https://java.sun.com/xml/ns/persistence

             https://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"

        version="2.0">

 

        <persistence-unit name="EmployeePU">

                <provider>org.hibernate.ejb.HibernatePersistence</provider>

                <properties>

                        <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/study" />

                        <property name="hibernate.connection.driver_class" value="com.mysql.cj.jdbc.Driver" />

                        <property name="hibernate.connection.username" value="root" />

                        <property name="hibernate.connection.password" value="root" />

                        <property name="hibernate.archive.autodetection" value="class" />

                        <property name="hibernate.show_sql" value="true" />

                        <property name="hibernate.format_sql" value="true" />

                        <property name="hbm2ddl.auto" value="update" />

                </properties>

        </persistence-unit>

</persistence>

Employee.java

package com.java4coding;

 

import javax.persistence.CascadeType;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.JoinColumn;

import javax.persistence.OneToOne;

import javax.persistence.Table;

 

@Entity

@Table(name="Employee")

public class Employee  {

 

        //Below @Column annotation is required, because there are two columns with the name EMPID

        //one in EMPLOYEE table and one in EMPLOYEEDETAIL table. If this field is not annotated with

        //@Column then while persisting Employee object JPA will get into conflict about where to persist this column

        //either to EMPLOYEE table or to the EMPLOYEEDETAIL table. We will persist only Employee object, due to the 121

        //relationship Employeedetail will also be persisted. So EMPID column of EMPLOYEEDETAIL table will be inserted

        //from Employee object, so both EMPID columns will be inserted through Employee object itself.

        @Id

        @Column(name = "EMPID")

        private int empid;

       

        private String name;

 

        @OneToOne(cascade = CascadeType.ALL )

        @JoinColumn(name = "EMPID")

        private Employeedetail employeedetails;

       

        //setters and getters

        public int getEmpid() {

                return empid;

        }

        public void setEmpid(int empid) {

                this.empid = empid;

        }

        public String getName() {

                return name;

        }

        public void setName(String name) {

                this.name = name;

        }

        public Employeedetail getEmployeedetails() {

                return employeedetails;

        }

        public void setEmployeedetails(Employeedetail employeedetails) {

                this.employeedetails = employeedetails;

        }

}

Employeedetail.java

package com.java4coding;

 

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.Table;

 

@Entity

@Table(name = "EMPLOYEEDETAIL")

public class Employeedetail  {

 

        @Id

        @GeneratedValue(strategy = GenerationType.AUTO)

        private int empdetailid;

 

        private int age;

       

        private String state;

       

        private int empid;

       

        public int getEmpdetailid() {

                return empdetailid;

        }

        public void setEmpdetailid(int empdetailid) {

                this.empdetailid = empdetailid;

        }

        public int getAge() {

                return age;

        }

        public void setAge(int age) {

                this.age = age;

        }

        public String getState() {

                return state;

        }

        public void setState(String state) {

                this.state = state;

        }

        public int getEmpid() {

                return empid;

        }

        public void setEmpid(int empid) {

                this.empid = empid;

        }

}

Test.java

package com.java4coding;

 

import javax.persistence.EntityManager;

import javax.persistence.EntityManagerFactory;

import javax.persistence.Persistence;

 

public class Test {

        public static void main(String[] args) {

                EntityManagerFactory emf = Persistence.createEntityManagerFactory("EmployeePU");

                EntityManager em = emf.createEntityManager();

 

                em.getTransaction().begin();

 

                Employee emp = new Employee();

                emp.setName("Manu Manjunatha");

                emp.setEmpid(1);

 

                Employeedetail empdetail = new Employeedetail();

                empdetail.setAge(26);

                empdetail.setState("Karnataka");

                empdetail.setEmpid(1);

 

                emp.setEmployeedetails(empdetail);

 

                em.persist(emp);

 

                // Employee can access EmployeeDetails

                Employee e = em.find(Employee.class, 1);

                System.out.println(e.getName());

                System.out.println(e.getEmployeedetails().getState());

 

                // EmployeeDetails can not access Employee

 

                em.getTransaction().commit();

        }

}

Project directory structure

jpa-one-to-one-unidirectional-association-mapping-0
 

Output:

Hibernate:

    insert

    into

        Employee

        (name, EMPID)

    values

        (?, ?)

Hibernate:

    insert

    into

        EMPLOYEEDETAIL

        (age, empid, state)

    values

        (?, ?, ?)

Manu Manjunatha

Karnataka

 


All Chapters
Author